<template>
  <div class="login-container">
    <div class="login-form-wrap">
      <div class="login-head">
        <div class="logo"></div>
      </div>
      <!-- 表单 -->
      <el-form ref="form" :rules="rules" :model="form">
        <!-- 手机号 -->
        <el-form-item prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <!-- 验证码 -->
        <el-form-item prop="code">
          <el-input v-model="form.code" placeholder="请输入验证码"></el-input>
        </el-form-item>
        <!-- 多选框 -->
        <el-form-item prop="isAgree">
          <el-checkbox v-model="form.isAgree"
            >我已阅读用户协议和隐私条款</el-checkbox
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login" class="login-btn"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { login } from '@/api'
import { setToken } from '@/utils/token.js'
export default {
  name: 'login',
  data () {
    return {
      form: {
        mobile: '13911111111', //手机号
        code: '246810', //验证码
        isAgree: true, // 是否已阅读
      },
      rules: {
        mobile: [
          { required: true, message: '请输入手机号', trigger: ['blur', 'change'] },
          { pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: ['blur', 'change'] }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: ['blur', 'change'] },
          { pattern: /^\d{6}$/, message: '请输入正确的验证码', trigger: ['blur', 'change'] }
        ],
        isAgree: [
          {
            validator: (rule, value, callback) => {
              value ? callback() : callback(new Error('请阅读隐私协议'))
            },
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    login () {
      console.log('refs:', this.$refs);
      this.$refs.form.validate(async value => {
        console.log('校验的结果', value);
        if (value) {
          //成功
          let res = await login(this.form)
          console.log(res);
          setToken(res.data.data.token)
          this.$message({
            message: '登陆成功',
            type: 'success'
          })
          this.$router.push('/layout')
        } else {
          //失败
          this.$message.error('校验失败')
        }
      })
    }
  }
}
</script>

<style lang="less">
// 铺满整屏
.login-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url('~@/assets/login_bg.jpg') no-repeat;
  background-size: cover;
  .login-form-wrap {
    width: 400px;
    padding: 30px 50px 10px;
    background-color: #fff;
    .login-head {
      display: flex;
      justify-content: center;
      .logo {
        width: 200px;
        height: 57px;
        background: url('~@/assets/logo_index.png') no-repeat;
        background-size: contain;
      }
    }
    .login-btn {
      width: 100%;
    }
  }
}
</style>